﻿using System.Diagnostics.CodeAnalysis;
using BaseData.CommonLib.Models;
using BaseData.CommonLib.Validators;
using BaseData.RazorLib.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Radzen;

namespace BaseData.RazorLib.Pages;

public partial class CalculateUnitEdit
{
    private CalculateUnitEditRequestDto _editRequestDto = new();
    private CalculateUnitEditValidator _editValidator = new();

    [Parameter]
    public int Key { get; set; }

    [Inject]
    [NotNull]
    public ICalculateUnitService CalculateUnitService { get; set; }

    [Inject] public DialogService DialogService { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        _editRequestDto = new CalculateUnitEditRequestDto();
        if (Key > 0)
        {
            var result = await CalculateUnitService.GetCalculateUnit(Key);
            if (result != null && result.Succeeded && result.Data != null)
            {
                _editRequestDto.Code = result.Data.Code;
                _editRequestDto.Name = result.Data.Name;
                _editRequestDto.Description = result.Data.Description;
            }
        }
    }


    async Task OnSubmit()
    {
        if (Key != null)
        {
            var result = await CalculateUnitService.UpdateCalculateUnit(Key, _editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
        else
        {
            var result = await CalculateUnitService.CreateCalculateUnit(_editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
    }


    protected void CancelButtonClick(MouseEventArgs args)
    {
        DialogService.Close(null);
    }

}